<template>
  <div class="resumes-management">
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索期望职位/技能"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddDialog">新增简历</el-button>
    </div>
    <el-table :data="filteredProfiles" style="margin-top:20px;">
      <el-table-column prop="profile_id" label="ID" width="60" />
      <el-table-column prop="user_id" label="用户ID" />
      <el-table-column prop="desired_position" label="期望职位" />
      <el-table-column prop="current_status" label="状态" />
      <el-table-column prop="experience_years" label="经验年限" />
      <el-table-column prop="expected_salary" label="期望薪资" />
      <el-table-column prop="education_level" label="教育水平" />
      <el-table-column prop="skills" label="技能" />
      <el-table-column prop="last_updated" label="更新时间" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editProfile(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteProfile(row.profile_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="用户ID">
          <el-input type="number" v-model="formData.user_id" :disabled="isEditing" />
        </el-form-item>
        <el-form-item label="期望职位">
          <el-input v-model="formData.desired_position" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.current_status" placeholder="选择状态">
            <el-option label="在职-考虑机会" value="在职-考虑机会" />
            <el-option label="离职-随时到岗" value="离职-随时到岗" />
            <el-option label="在校学生" value="在校学生" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验年限">
          <el-input type="number" v-model="formData.experience_years" />
        </el-form-item>
        <el-form-item label="期望薪资">
          <el-input v-model="formData.expected_salary" />
        </el-form-item>
        <el-form-item label="教育水平">
          <el-input v-model="formData.education_level" />
        </el-form-item>
        <el-form-item label="技能">
          <el-input type="textarea" v-model="formData.skills" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const auth = useAuthStore()
const profiles = ref([])
const searchQuery = ref('')
const dialogVisible = ref(false)
const isEditing = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  profile_id: null,
  user_id: auth.userId,
  desired_position: '',
  current_status: '',
  experience_years: null,
  expected_salary: '',
  education_level: '',
  skills: ''
})

// 添加过滤后的简历列表计算属性
const filteredProfiles = computed(() => {
  if (!searchQuery.value) return profiles.value
  const query = searchQuery.value.toLowerCase()
  return profiles.value.filter(profile => 
    profile.desired_position.toLowerCase().includes(query) ||
    profile.skills.toLowerCase().includes(query)
  )
})

// 添加搜索处理方法
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

const fetchProfiles = async () => {
  try {
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    profiles.value = await res.json()
  } catch (err) {
    ElMessage.error('获取简历列表失败: ' + err.message)
  }
}

const showAddDialog = () => {
  isEditing.value = false
  dialogTitle.value = '新增简历'
  Object.assign(formData, { profile_id: null, user_id: auth.userId, desired_position: '', current_status: '', experience_years: null, expected_salary: '', education_level: '', skills: '' })
  dialogVisible.value = true
}

const editProfile = (row) => {
  isEditing.value = true
  dialogTitle.value = '编辑简历'
  Object.assign(formData, {
    profile_id: row.profile_id,
    user_id: row.user_id,
    desired_position: row.desired_position,
    current_status: row.current_status,
    experience_years: row.experience_years,
    expected_salary: row.expected_salary,
    education_level: row.education_level,
    skills: row.skills
  })
  dialogVisible.value = true
}

const saveProfile = async () => {
  try {
    if (!formData.desired_position || !formData.current_status) {
      ElMessage.warning('请填写必要信息')
      return
    }
    const token = auth.token
    let res
    const payload = { ...formData }
    if (isEditing.value) {
      res = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles/${formData.profile_id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify(payload)
      })
    } else {
      res = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify(payload)
      })
    }
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || '操作失败')
    ElMessage.success('保存成功')
    fetchProfiles()
    dialogVisible.value = false
  } catch (err) {
    ElMessage.error(err.message)
  }
}

const deleteProfile = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该简历吗？', '提示', { type: 'warning' })
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles/${id}?user_id=${auth.userId}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchProfiles()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error(err.message || '删除失败')
  }
}

onMounted(fetchProfiles)
</script>

<style scoped>
.resumes-management {
  padding: 20px;
}
.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.search-input {
  width: 300px;
}
</style> 